#include <QMessageBox>
#include <QStringList>

#include "formeditfeed.h"
#include "definitions.h"


FormEditFeed::FormEditFeed(RssReader *reader, QWidget *parent, const QString &suggestedCategory, const QString &link) : QDialog(parent), ui(new Ui::FormEditFeed) {
    ui->setupUi(this);
    this->reader = reader;
    this->oldFeed = NULL;

    connect(ui->btnHelp, SIGNAL(clicked()), this, SLOT(showHelp()));
    connect(ui->btnTest, SIGNAL(clicked()), this, SLOT(testLink()));
    connect(ui->txtTitle, SIGNAL(textChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->txtLink, SIGNAL(textChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->cmbCategory, SIGNAL(editTextChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->cmbEnc, SIGNAL(editTextChanged(QString)), this, SLOT(checkFeed()));
    connect(ui->txtNextLink, SIGNAL(textChanged(QString)), this, SLOT(checkLink()));
    connect(ui->btnNextLink, SIGNAL(clicked()), this, SLOT(advance()));
    connect(ui->txtLink, SIGNAL(textChanged(QString)), this, SLOT(showAuthThings()));
    connect(ui->txtNextLink, SIGNAL(textChanged(QString)), this, SLOT(showAuthThings()));

    ui->txtLink->setPlaceholderText(link);
    ui->txtNextLink->setPlaceholderText(link);
    ui->txtNextLink->setText(link);

    foreach (QString category, this->reader->getCategories()) {
	ui->cmbCategory->addItem(category);
	if (category == suggestedCategory)
	    ui->cmbCategory->setCurrentIndex(ui->cmbCategory->count()-1);
    }

    if (this->reader->getCategories().size() == 0)
	ui->cmbCategory->setEditText(tr("Your new category's title"));
    QList<QByteArray> encodings = QTextCodec::availableCodecs();
    QStringList encodi;
    foreach (QByteArray encod, encodings) {
	encodi.append(QString(encod));
    }
    encodi.sort();
    ui->cmbEnc->addItems(encodi);
}

FormEditFeed::~FormEditFeed() {
    delete ui;
}

void FormEditFeed::advance() {
    ui->txtLink->setText(ui->txtNextLink->text());
    ui->txtSecondPassword->setText(ui->txtFirstPassword->text());
    ui->txtSecondUsername->setText(ui->txtFirstUsername->text());
    testLink(ui->txtLink->text());
    ui->stackedWidget->setCurrentIndex(ui->stackedWidget->currentIndex()+1);
}

void FormEditFeed::showAuthThings() {
    bool show = ui->txtLink->text().contains("https") || ui->txtNextLink->text().contains("https");

    ui->txtFirstPassword->setVisible(show);
    ui->txtFirstUsername->setVisible(show);
    ui->lblFirstPassword->setVisible(show);
    ui->lblFirstUsername->setVisible(show);

    ui->txtSecondPassword->setVisible(show);
    ui->txtSecondUsername->setVisible(show);
    ui->lblSecondPassword->setVisible(show);
    ui->lblSecondUsername->setVisible(show);
}

RssFeed *FormEditFeed::editFeed(RssFeed *oldFeed) {
    if (oldFeed != NULL) {
	this->oldFeed = oldFeed;
	setWindowTitle(tr("Edit feed"));
	ui->txtTitle->setText(this->oldFeed->getTitle());
	ui->txtLink->setText(this->oldFeed->getLink());
	ui->cmbCategory->setEditText(this->oldFeed->getCategory());
	ui->cmbType->setCurrentIndex(this->oldFeed->getType() - RssgTypes::FEED_UNKNOWN - 1);
	ui->cmbEnc->setEditText(this->oldFeed->getEncoding());
	ui->txtSecondUsername->setText(this->oldFeed->getUsername());
	ui->txtSecondPassword->setText(this->oldFeed->getPassword());
	ui->stackedWidget->setCurrentIndex(1);
	ui->txtLink->selectAll();
	ui->txtLink->setFocus();
    }
    ui->txtNextLink->selectAll();
    ui->txtNextLink->setFocus();
    if (this->exec() == QDialog::Accepted) {
	RssFeed *feed = new RssFeed(ui->txtTitle->text(), ui->txtLink->text(), ui->cmbCategory->currentText(), RssFactory::intToFeedType(ui->cmbType->currentIndex() + 1 + (int) RssgTypes::FEED_UNKNOWN), ui->cmbEnc->currentText());
	feed->setUsername(ui->txtSecondUsername->text());
	feed->setPassword(ui->txtSecondPassword->text());
	return feed;
    }
    else {
	return NULL;
    }
}

void FormEditFeed::checkLink() {
    QString url = ui->txtNextLink->text();
    // Safari uses URL: feed://foo.bar/...
    if (url.startsWith("feed://")) {
	url = url.replace(QRegExp("^feed"), "http");
	ui->txtNextLink->setText(url);
	// it's fine to return here. We will get another call
	// immediately due setText()
	return;
    }
    // and feed:html:// sometimes too
    if (url.startsWith("feed:http")) {
	url = url.replace(QRegExp("^feed:http"), "http");
	ui->txtNextLink->setText(url);
	// it's fine to return here. We will get another call
	// immediately due setText()
	return;
    }
    ui->btnNextLink->setEnabled(RssFactory::isValid(QList<QString>() << url));
}

void FormEditFeed::checkFeed() {
    QStringList toCheck;
    toCheck << ui->txtTitle->text() << ui->txtLink->text() << ui->cmbEnc->currentText();
    // do not check ui->cmbCategory->currentText() against VALID_LIMIT. I want 2 chars catogory too.
    // also an empty caategory can be valid later
    QString category = ui->cmbCategory->currentText();
    if (category.isEmpty())
	category = tr("Default");

    if (RssFactory::isValid(toCheck)) {
	if (!oldFeed && reader->canBeAdded(ui->txtTitle->text(), ui->txtLink->text()))
	    ui->btnOk->setEnabled(true);
	else if (oldFeed && reader->canBeEdited(oldFeed, new RssFeed(ui->txtTitle->text(), ui->txtLink->text(), category, RssFactory::intToFeedType(ui->cmbType->currentIndex() + 1 + (int) RssgTypes::FEED_UNKNOWN), ui->cmbEnc->currentText())))
	    ui->btnOk->setEnabled(true);
	else
	    ui->btnOk->setEnabled(false);
    }
    else {
	ui->btnOk->setEnabled(false);
    }
}

void FormEditFeed::showHelp() {
    QMessageBox::information(this, tr("Help"), tr("Title must be at least one character long.\n\nNote also that you can write your own names for category, you don't have to select predefined ones. The \"Test by link\" button is for testing if feed exists and you have to have link written in dialog already."));
}

bool FormEditFeed::testLink(const QString &link) {
    QString realLink = link == "" ? ui->txtLink->text() : link;
    QString *title = new QString();
    QList<QString> auths;
    auths.append(ui->txtSecondUsername->text()); auths.append(ui->txtSecondPassword->text());
    RssgTypes::FeedType type = RssFactory::guessFeed(realLink, title,
						     !ui->txtSecondUsername->text().isEmpty(),
						     auths);
    switch (type) {
	case RssgTypes::FEED_UNKNOWN:
	    QMessageBox::critical(this, tr("Feed doesn't exist"), tr("This feed doesn't exist or its unreachable. Please double-check url which you provided. You may have to input other details of feed by yourself."));
	    return false;
	case RssgTypes::FEED_ATOM:
	case RssgTypes::FEED_RSS:
	    QMessageBox::information(this, tr("Feed exists"), tr("It seems, that this feed exists and is accessible. You can add this feed without problems.\n\nObtained name: %1\nObtained type: %2\nObtained encoding: %3").arg(title->split(',').at(1), RssFactory::feedTypeToQstring(type), title->split(',').at(0).size() > 0 ? title->split(',').at(0) : tr("NO ENCODING FOUND, USING UTF-8")));
	    break;
    }
    ui->txtTitle->setText(title->split(',').at(1));
    if (title->split(',').at(0).size() > 0)
	ui->cmbEnc->setEditText(title->split(',').at(0));
    else
	ui->cmbEnc->setEditText("UTF-8");
    ui->cmbType->setCurrentIndex(type - RssgTypes::FEED_UNKNOWN - 1);
    return true;
}
